package com.gl.common.listener;

import com.mysql.jdbc.AbandonedConnectionCleanupThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

/**
 * 此Listener用于释放数据库连接线程（这是mysql导致的bug）
 *
 * @author 
 * @date
 */
@WebListener
public class AbandonedConnectionCleanupTheardListener implements ServletContextListener {
    private static Logger logger = LoggerFactory.getLogger(AbandonedConnectionCleanupTheardListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        logger.info("AbandonedConnectionCleanupTheardListener is started.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        Enumeration<Driver> drivers = DriverManager.getDrivers();

        // 清除驱动
        while (drivers != null && drivers.hasMoreElements()) {
            try {
                Driver driver = drivers.nextElement();
                DriverManager.deregisterDriver(driver);
                logger.info("注销数据库连接线程成功。");
            } catch (SQLException ex) {
                logger.error("注销数据库连接线程失败（这种情况通常出现在MySQL上）。");
            }
        }

        // MySQL driver leaves around a thread. This static method cleans it up.
        try {
            AbandonedConnectionCleanupThread.shutdown();
            logger.info("AbandonedConnectionCleanupThread线程关闭成功。");
        } catch (RuntimeException e) {
            logger.error("AbandonedConnectionCleanupThread线程关闭失败（这种情况通常出现在MySQL上）。");
        }
    }
}
